package com.devops.admin.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.devops.admin.model.DOSResource;
import com.devops.admin.po.MattermostOutgoingRequest;
import com.devops.admin.po.MattermostOutgoingResponse;
import com.devops.admin.service.DOSResourceService;
import com.devops.admin.util.Assert;
import com.devops.common.utils.Message;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.Optional;

/**
 * @author jxt
 * @Notes
 * @date 2023/3/20 16:22
 */
@Slf4j
@RestController
@RequestMapping("/api/robot")
@Api(value = "/api/robot",tags = "机器人相关接口")
public class RobotController {

    @Resource
    DOSResourceService resourceService;

    @PostMapping(value = "/notify")
    @ApiOperation(value="钉钉机器人通知地址",notes = "钉钉机器人通知地址")
    public Message callBack(@RequestBody JSONObject jsonObject) {
        log.info("ding talk robot notify {}", jsonObject);
        return Message.ok("操作成功");
    }

    @PostMapping(value = "/command")
    @ApiOperation(value="发送消息",notes = "发送消息")
    public Object send(@RequestBody JSONObject requestJson) {
        log.info("command {}", requestJson);
        MattermostOutgoingRequest request = JSONUtil.toBean(requestJson, MattermostOutgoingRequest.class);
        Assert.isTrue(Objects.equals(request.getTeamDomain(), "ijx"), "invalid request");
        log.info(request.toString());
        MattermostOutgoingResponse response = new MattermostOutgoingResponse();
        switch(request.getTriggerWord()) {
            case "redis":
                response.setText(getRedisKey(request));
                break;
            case "hello":
                response.setText("hi");
                break;
            default:
                request.setText("undefined command");
                break;
        }
        return response;
    }

    private String getRedisKey(MattermostOutgoingRequest request) {
        MattermostOutgoingResponse response = new MattermostOutgoingResponse();
        String[] params = request.getText().split(" ");
        // 参数校验
        if (params.length < 3 || params.length > 5) {
            return "params error";
        }

        String redisName = params[1].trim();
        int db = 0;
        String key = params[2].trim();

        // 如果有第四个参数，尝试解析数据库索引
        if (params.length > 3) {
            try {
                db = Integer.parseInt(params[3].trim());
            } catch (NumberFormatException e) {
                return "database index format error";
            }
        }

        // 查找对应的Redis资源
        Optional<DOSResource> resourceOpt = resourceService.getRedisList().stream()
                .filter(r -> r.getName().equals(redisName))
                .findFirst();

        if (!resourceOpt.isPresent()) {
            return "target redis not found";
        }

        DOSResource resource = resourceOpt.get();

        try (Jedis jedis = new Jedis(resource.getIp(), Integer.parseInt(resource.getPort()))) {
            // 认证（支持密码为空）
            if (StrUtil.isNotEmpty(resource.getUsers()) && StrUtil.isNotEmpty(resource.getPassword())) {
                jedis.auth(resource.getUsers(), resource.getPassword());
            } else if (StrUtil.isNotEmpty(resource.getPassword())) {
                jedis.auth(resource.getPassword());
            }

            jedis.select(db);

            String keyValue = jedis.get(key);
            return StrUtil.isNotBlank(keyValue) ? keyValue : StrUtil.format("redis key \"{}\" not found", key);
        } catch (Exception e) {
            return "Error processing request: " + e.getMessage();
        }
    }
}
